package com.kf.bigbluebook.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kf.bigbluebook.model.po.User;
import com.kf.bigbluebook.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/***
 * 对用户推荐进行缓存预热
 */
@Component
@Slf4j
public class preCacheJob {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private RedissonClient redissonClient;

    /***
     * 对推荐用户进行缓存预热
     */
    @Scheduled(cron = "0 0 0 * * ?")
//    @Scheduled(cron = "0 */1 * * * ?")
    public void preCache() {
        RLock lock = redissonClient.getLock("kf:bigbluebook:lock");
        try {
            //获取锁实现原子操作
            if (lock.tryLock(0, -1, TimeUnit.MILLISECONDS)) {
                System.out.println("lock:" + Thread.currentThread().getId());
//                Thread.sleep(30000);
                //获取比较活跃的用户对其推荐用户进行缓存预热，这里假设为20个
                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                Page<User> userPage = userService.page(new Page<User>(1, 20), queryWrapper);
                List<User> userList = userPage.getRecords();
                //获取推荐用户，这里假设为前10个
                Page<User> recommendUsers = userService.page(new Page<User>(1, 10), queryWrapper);
                //缓存到redis中
                ValueOperations<String, Object> operations = redisTemplate.opsForValue();
                for (User user : userList) {
                    String redisKey = String.format("kf:bigbluebook:userId=%s", user.getId());
                    try {
                        operations.set(redisKey, recommendUsers, 6, TimeUnit.HOURS);
                    } catch (Exception e) {
                        log.error("recommendUsers cache error", e);
                    }
                }
                log.info("recommendUsers cache success");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //当前进程持有锁，则释放锁
            if (lock.isHeldByCurrentThread()) {
                System.out.println("unlock:" + Thread.currentThread().getId());
                lock.unlock(); //释放锁
            }
        }

    }
}
